import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:macnov/services/auth.dart';
import 'package:macnov/stores/signin.dart';
import 'package:macnov/utils/constant.dart';
import 'package:passcode_screen/circle.dart';
import 'package:passcode_screen/keyboard.dart';
import 'package:passcode_screen/passcode_screen.dart';

class LoginOptions extends StatefulWidget {
  @override
  _LoginOptionsState createState() => _LoginOptionsState();
}

const PIN_CHOOSE = 'Choose 4 digit PIN';
const PIN_CHOOSE_AGAIN = 'Re-enter your pin';

class _LoginOptionsState extends State<LoginOptions> {
  final StreamController<bool> _verificationNotifier =
      StreamController<bool>.broadcast();

  String pinCodeStatus = PIN_CHOOSE;
  String pinCodePassword;
  LoginOpt lastLoginOption;

  @override
  void initState() {
    super.initState();
    _loadLastLoginOpt();
  }

  void _loadLastLoginOpt() async {
    LoginOpt opt = await signInStore.loadLastLoginOption();
    setState(() {
      lastLoginOption = opt;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        iconTheme: IconThemeData(color: Colors.black),
        elevation: 0.0,
        title: Text('LOGIN OPTIONS',style: TextStyle(color: Colors.black87),),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            margin: EdgeInsets.all(10),
            height: 60,
            child: Center(
              child: Text(
                'How would you like to log in to Macnov in the future?',
                style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w400),
              ),
            ),
          ),
          Card(
            child: Column(
              children: <Widget>[
                new ListTile(
                  onTap: () => this._authPINCode(),
                  title: new Text('PIN',
                      style: new TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 18)),
                  subtitle: new Text('Create a PIN to log in to Macnov',
                      style: new TextStyle(fontWeight: FontWeight.w500)),
                  trailing: lastLoginOption == LoginOpt.PIN
                      ? (Icon(
                          Icons.check,
                          size: 42,
                        ))
                      : null,
                ),
                new Divider(),
                new ListTile(
                  onTap: () => this._authEmail(),
                  title: new Text('Email and password',
                      style: new TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 18)),
                  subtitle: new Text(
                      'Require your email and password each time',
                      style: new TextStyle(fontWeight: FontWeight.w500)),
                  trailing: lastLoginOption == LoginOpt.EMAIL
                      ? (Icon(
                          Icons.check,
                          size: 42,
                        ))
                      : null,
                ),
                new Divider(),
                new ListTile(
                  onTap: () => this._authBiology(),
                  title: new Text('Touch ID',
                      style: new TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 18)),
                  subtitle: new Text('Enable Touch ID to log in to Macnov',
                      style: new TextStyle(fontWeight: FontWeight.w500)),
                  trailing: lastLoginOption == LoginOpt.TOUCHID
                      ? (Icon(
                          Icons.check,
                          size: 42,
                        ))
                      : null,
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  void _authBiology() async {
    bool canCheckBiometrics = await authService.checkBiometrics();
    print("canCheckBiometrics $canCheckBiometrics");
    if (canCheckBiometrics) {
      bool authenticated = await authService.authenticate();
      print("authenticated $authenticated");
      if (authenticated) {
        signInStore.saveLastLoginOption(LoginOpt.TOUCHID, '');
        setState(() {
          lastLoginOption = LoginOpt.TOUCHID;
        });
      }
    }
  }

  void _authEmail() async {
    signInStore.saveLastLoginOption(LoginOpt.EMAIL, '');
    setState(() {
      lastLoginOption = LoginOpt.EMAIL;
    });
  }

  void _authPINCode() async {
    _showLockScreen(context, opaque: true);
  }

  _showLockScreen(BuildContext context,
      {bool opaque,
      CircleUIConfig circleUIConfig,
      KeyboardUIConfig keyboardUIConfig}) {
    Navigator.push(
        context,
        PageRouteBuilder(
          opaque: opaque,
          pageBuilder: (context, animation, secondaryAnimation) =>
              PasscodeScreen(
            title: '$pinCodeStatus',
            circleUIConfig: circleUIConfig,
            keyboardUIConfig: keyboardUIConfig,
            passwordEnteredCallback: _onPasscodeEntered,
            passwordDigits: 4,
            cancelLocalizedText: 'Cancel',
            deleteLocalizedText: 'Delete',
            shouldTriggerVerification: _verificationNotifier.stream,
            backgroundColor: Colors.black.withOpacity(0.8),
            cancelCallback: _onPasscodeCancelled,
          ),
        ));
  }

  _onPasscodeEntered(String enteredPasscode) {
    if (pinCodePassword == null) {
      print('_onPasscodeEntered $enteredPasscode first');
      setState(() {
        pinCodePassword = enteredPasscode;
        pinCodeStatus = PIN_CHOOSE_AGAIN;
      });
      _verificationNotifier.add(true);
      // _showLockScreen(context, opaque: true);
    } else {
      bool isValid = pinCodePassword == enteredPasscode;
      _verificationNotifier.add(isValid);
      if (isValid) {
        _resetPINCodeOK();
      }
    }
  }

  _resetPINCodeOK() {
    print(
      'PIN_CHOOSE_AGAIN $pinCodePassword',
    );
    signInStore.saveLastLoginOption(LoginOpt.PIN, pinCodePassword);
    setState(() {
      lastLoginOption = LoginOpt.PIN;
    });
    _resetPINCode();
  }

  _resetPINCode() {
    setState(() {
      pinCodePassword = null;
      pinCodeStatus = PIN_CHOOSE;
    });
  }

  _onPasscodeCancelled() {
    print('_onPasscodeCancelled#####');
    _resetPINCode();
  }

  @override
  void dispose() {
    _verificationNotifier.close();
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    super.dispose();
  }
}
